<!--
 * @Author: your name
 * @Date: 2021-09-03 14:03:56
 * @LastEditTime: 2021-09-07 11:26:37
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \ej-webui\src\pages\production\index.vue
-->
<template>
  <div>
    <el-form :inline="true" :model="params" class="demo-form-inline">
      <el-form-item>
        <el-button type="primary" size="small" @click="addHandler"
          >添加</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="params.name"
          placeholder="请输入名称"
          size="small"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-select
          v-model="params.status"
          placeholder="请选择状态"
          size="small"
          clearable
        >
          <el-option label="正常" value="正常"></el-option>
          <el-option label="下架" value="下架"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select
          v-model="params.productCategoryId"
          placeholder="请选择栏目"
          size="small"
          clearable
        >
          <el-option
            v-for="c in categories"
            :key="c.id"
            :label="c.name"
            :value="c.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="pageQueryProductions()"
          >查询</el-button
        >
      </el-form-item>
    </el-form>
    <el-table style="width: 100%" :data="resData.list" size="small">
      <el-table-column type="index" label="序号" width="50"> </el-table-column>
      <el-table-column label="产品编号" width="180" prop="id">
      </el-table-column>
      <el-table-column label="名称" width="230" prop="name"> </el-table-column>
      <el-table-column label="图片" width="180">
        <template v-slot="scope">
          <el-popover placement="right" width="225" trigger="hover">
            <img :src="scope.row.photo" alt="图片丢失" width="200" />
            <div slot="reference">
              <img :src="scope.row.photo" alt="图片丢失" width="50" />
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="价格" width="100">
        <template v-slot="scope"> {{ scope.row.price }}￥ </template>
      </el-table-column>
      <el-table-column label="状态" width="180" prop="status">
        <template v-slot="scope">
          <el-tag
            v-if="scope.row.status == '正常'"
            size="mini"
            type="success"
            >{{ scope.row.status }}</el-tag
          >
          <el-tag v-else size="mini" type="danger">{{
            scope.row.status
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="所属栏目" width="180" prop="category.name">
      </el-table-column>
      <el-table-column label="操作">
        <template v-slot="scope">
          <el-button type="text" @click="changeTable(scope.row)"
            >编辑</el-button
          >
          <el-button
            type="text"
            v-if="scope.row.status == '正常'"
            @click="changeStatus(scope.row.id, $event)"
            style="color: red"
            >下架</el-button
          >
          <el-button
            v-else
            type="text"
            style="color: green"
            @click="changeStatus(scope.row.id, $event)"
            >上架</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="float: right; margin-top: 10px"
      layout="total,sizes,prev, pager, next,jumper"
      :total="resData.total"
      :page-size="params.pageSize"
      :current-page="params.page"
      @current-change="pageChangeHandler"
      :page-sizes="[5, 10, 15]"
      @size-change="sizeChangeHandler"
      size="small"
    >
    </el-pagination>
    <!-- 模态框 -->
    <el-dialog
      :title="title"
      :visible.sync="visible"
      @close="dialogCloseHandler"
    >
      <el-form :model="production" :rules="rules" ref="saveForm">
        <el-form-item
          label="产品名称"
          :label-width="formLabelWidth"
          prop="name"
        >
          <el-input v-model="production.name"></el-input>
        </el-form-item>
        <el-form-item
          label="所属栏目"
          :label-width="formLabelWidth"
          prop="productCategoryId"
        >
          <el-select
            v-model="production.productCategoryId"
            placeholder="请选择所属栏目"
          >
            <el-option
              v-for="c in categories"
              :label="c.name"
              :value="c.id"
              :key="c.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="价格" :label-width="formLabelWidth" prop="price">
          <el-input v-model="production.price"></el-input>
        </el-form-item>
        <el-form-item
          label="产品图片"
          :label-width="formLabelWidth"
          prop="photo"
        >
          <el-upload
            class="avatar-uploader"
            action="http://81.69.24.232/pet/jz_upload.php"
            :show-file-list="false"
            :on-success="handlePhotoSuccess"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="产品描述" :label-width="formLabelWidth">
          <el-input type="textarea" v-model="production.description"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="toSaveHandler">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request"
import { mapActions } from "vuex"
import qs from 'qs'
import _ from 'lodash'  //克隆
export default {
  data() {
    return {
      params: {
        page: 1,
        pageSize: 5
      },
      resData: {},
      categories: [],
      title: '',
      visible: false,
      production: {},
      formLabelWidth: '80px',
      imageUrl: null,
      rules: {
        name: [
          { required: true, message: '请输入产品名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        productCategoryId: [
          { required: true, message: '请选择所属栏目', trigger: 'change' }
        ],
        price: [
          { required: true, message: '请输入产品价格', trigger: 'blur' }
        ],
        photo: [
          { required: true, message: '请上传产品封面', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    //导入vuex中的方法
    ...mapActions('category', ['findAllCategories']),
    //设置为异步函数
    async pageQueryProductions() {
      for (let key in this.params) {
        if (this.params[key] == '') {
          delete this.params[key]
        }
      }
      let res = await request.get("/product/pageQuery", {
        params: this.params
      })
      this.resData = res.data
    },
    //页面改变
    pageChangeHandler(page) {
      this.params.page = page
      this.pageQueryProductions()
    },
    //分页数量改变
    sizeChangeHandler(pageSize) {
      this.params.pageSize = pageSize
      this.pageQueryProductions()
    },
    //     //查询产品
    //     findCategory() {
    //       this.pageQueryProductions()
    //     },
    addHandler() {
      this.imageUrl = null
      this.production = {}
      this.title = '添加产品信息'
      this.visible = true
    },
    handlePhotoSuccess(res, file) {
      this.production.photo = res
      this.imageUrl = res
    },
    toSaveHandler() {
      //qs.stringify 转换为表单数据
      this.$refs['saveForm'].validate((valid) => {
        if (valid) {
          request.post("/product/saveOrUpdate", qs.stringify(this.production)).then(res => {
            this.pageQueryProductions()
            this.$message.success(res.message)   //提示操作结果
            this.visible = false
          })
        } else {
          return false
        }
      })
    },
    dialogCloseHandler() {
      this.$refs["saveForm"].resetFields(); // 置空表单验证
    },
    changeTable(row) {
      this.production = _.clone(row)   //将当前行数据复制给数据模型
      this.imageUrl = row.photo
      this.title = '编辑产品信息'
      this.visible = true
    },
    changeStatus(id, e) {
      this.$confirm('是否确认该操作', '提示', {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        if (e.target.innerText == '下架') {
          request.get('/product/offline', { params: { id } }).then(res => {
            this.pageQueryProductions(); // 重载数据
            this.$message.success(res.message); // 提示信息
          })
        } else {
          request.get('/product/online', { params: { id } }).then(res => {
            this.pageQueryProductions(); // 重载数据
            this.$message.success(res.message); // 提示信息
          })
        }
      })
    }
  },
  //重新渲染页面
  created() {
    this.pageQueryProductions()
    this.findAllCategories().then(res => {
      this.categories = res.data.list
    })
  }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>